package com.learn.english.controller;

import com.learn.english.domain.LoginUserVO;
import com.learn.english.domain.R;
import com.learn.english.enums.ResultCode;
import com.learn.english.exception.BusinessException;
import com.learn.english.model.dto.LoginDto;
import com.learn.english.service.ICodeService;
import com.learn.english.service.ILoginService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author TISNIW
 * @version 1.0
 * @date 2024/6/25 22:47
 * @desc
 */
@RestController
@Slf4j
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private ILoginService loginService;
    @Autowired
    private ICodeService codeService;
    @PostMapping("/")
    public R<LoginUserVO> login(@RequestBody LoginDto loginDto) {
        try {
            return R.ok(loginService.login(loginDto));
        }catch (IllegalArgumentException e) {
            throw new BusinessException(ResultCode.FAIL);
        }
    }
    @PostMapping("/email")
    public R<LoginUserVO> emailLogin(@RequestBody LoginDto loginDto, HttpSession session) {
        if (codeService.verifyCode(loginDto.getCode(),session)){
            try {
                return R.ok(loginService.emailLogin(loginDto));
            }catch (IllegalArgumentException e) {
                throw new BusinessException(ResultCode.FAIL);
            }
        }
        return R.fail(ResultCode.CODE_TIMEOUT);
    }
}
